// 项目中的工具方法 exp： isArray isFunction...
import { AxiosResponse } from 'axios';
import { LoginProps, RegisterProps } from '../api/types'
import md5 from 'md5'
// 得到响应的的data
export const getResponseData = <T>(r: AxiosResponse): T => {
    return r.data;
}

// 对密码进行加密
export const encryption = (props: RegisterProps | LoginProps): RegisterProps | LoginProps => {
    return { ...props, password: md5(props.password) }
}

/**
 * 从session中获取执行的值
 * @param key 
 */
export const getSessionStore = (key: string): any => {
    let val;
    try {
        val = sessionStorage.getItem(key);
        if (val) {
            return parse(val);
        }
    } catch (e) {
        val = sessionStorage.getItem(key);
    }
    return val
}

/**
 * 给session 存值
 * @param key 
 * @param val 
 */
export const setSessionStore = (key: string, val: any): void => {
    if (isObject(val)) {
        val = stringify(val);
    }
    sessionStorage.setItem(key, val)
}

/**
 * 清除掉session中的某一个字段
 * @param key 
 */
export const removeSessionStore = (key: string): void => {
    sessionStorage.removeItem(key);
}

/**
 * 退出登录或者校验登录信息不成功时清除掉session中的信息
 */
export const removeLogoutMsgFromSessionStore = (): void => {
    removeSessionStore('user');
    removeSessionStore('token');
}

// 判断是不是对象类型
export const isObject = (val: object): boolean => typeof val === 'object';

//字符串化
export const stringify = (val: object): string => JSON.stringify(val);

// 转化字符串为对象
export const parse = (val: string): object => JSON.parse(val);